<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Atomic,">










<meta name="description" content="原子类 当程序更新一个变量时，如果多线程更新会产生期望之外的值，比如在进行i++，虽然volatile可以保证可见性，但是无法保证原子性，即使使用synchronized可以保证多线程下不会出现误差，但是会阻塞线程、性能较低。1.5之后，jdk提供了Atomic包，这个包中的原子类提供了一种简单高效、线程安全的更新变量，那么synchronized是不是就不用了呢，其实不然，后续会说原子类的缺点。">
<meta name="keywords" content="Atomic">
<meta property="og:type" content="article">
<meta property="og:title" content="Java并发编程五Atomic原子类">
<meta property="og:url" content="https://zgsir.gitee.io/blog/2019/05/27/Java并发编程五Atomic原子类/index.html">
<meta property="og:site_name" content="zhaoSir">
<meta property="og:description" content="原子类 当程序更新一个变量时，如果多线程更新会产生期望之外的值，比如在进行i++，虽然volatile可以保证可见性，但是无法保证原子性，即使使用synchronized可以保证多线程下不会出现误差，但是会阻塞线程、性能较低。1.5之后，jdk提供了Atomic包，这个包中的原子类提供了一种简单高效、线程安全的更新变量，那么synchronized是不是就不用了呢，其实不然，后续会说原子类的缺点。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/27/VZflgs.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/27/VZfQ3j.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/27/VZfMCQ.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/27/VZfu4g.png">
<meta property="og:updated_time" content="2019-05-27T11:25:43.387Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java并发编程五Atomic原子类">
<meta name="twitter:description" content="原子类 当程序更新一个变量时，如果多线程更新会产生期望之外的值，比如在进行i++，虽然volatile可以保证可见性，但是无法保证原子性，即使使用synchronized可以保证多线程下不会出现误差，但是会阻塞线程、性能较低。1.5之后，jdk提供了Atomic包，这个包中的原子类提供了一种简单高效、线程安全的更新变量，那么synchronized是不是就不用了呢，其实不然，后续会说原子类的缺点。">
<meta name="twitter:image" content="https://s2.ax1x.com/2019/05/27/VZflgs.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zgsir.gitee.io/blog/2019/05/27/Java并发编程五Atomic原子类/">





  <title>Java并发编程五Atomic原子类 | zhaoSir</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhaoSir</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个不正经的后台开发攻城狮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zgsir.gitee.io/blog/blog/2019/05/27/Java并发编程五Atomic原子类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaoSir">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/head.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhaoSir">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java并发编程五Atomic原子类</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-27T19:16:55+08:00">
                2019-05-27
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-05-27T19:25:43+08:00">
                2019-05-27
              </time>
            
          </span>
          
          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java并发/" itemprop="url" rel="index">
                    <span itemprop="name">Java并发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye"></i> 阅读
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.9k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="原子类"><a href="#原子类" class="headerlink" title="原子类"></a>原子类</h1><p> 当程序更新一个变量时，如果多线程更新会产生期望之外的值，比如在进行i++，虽然volatile可以保证可见性，但是无法保证原子性，即使使用synchronized可以保证多线程下不会出现误差，但是会阻塞线程、性能较低。1.5之后，jdk提供了Atomic包，这个包中的原子类提供了一种简单高效、线程安全的更新变量，那么synchronized是不是就不用了呢，其实不然，后续会说原子类的缺点。</p>
<h1 id="原子更新基本类型"><a href="#原子更新基本类型" class="headerlink" title="原子更新基本类型"></a>原子更新基本类型</h1><p> <strong>使用原子的方式更新基本类型。</strong>Atomic提供了三个：AtomicBoolean原子更新布尔类型，AtomicInteger原子更新整数类型，AtomicLong原子更新长整型。<br> 常用方法如下：<br> int addAndGet（int delta）：以原子方式将输入的数值与实例中的值（AtomicInteger里的<br>value）相加，并返回结果。<br>boolean compareAndSet（int expect，int update）：如果输入的数值等于预期值，则以原子方<br>式将该值设置为输入的值。<br> void lazySet（int newValue）：最终会设置成newValue，使用lazySet设置值后，可能导致其他<br>线程在之后的一小段时间内还是可以读到旧的值。<br>int getAndSet（int newValue）：以原子方式设置为newValue的值，并返回旧值。<br>int getAndIncrement()：以原子方式将当前值加1，注意，这里返回的是自增前的值。<br>int getAndDecrement( )：以原子方式将当前值减1，注意，这里返回的是自减前的值。<br>int incrementAndGet()：以原子方式将当前值加1，返回的是自增后的值。<br>int decrementAndGet()：以原子方式将当前值减1，返回的是自减后的值。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">       // 定义一个原子整数类初始值为0</span><br><span class="line">       AtomicInteger atomicInteger = new AtomicInteger(0);</span><br><span class="line">       // 开启十个线程 每个线程执行一百次</span><br><span class="line">       for (int i = 0; i &lt;10 ; i++) &#123;</span><br><span class="line">           new Thread(()-&gt;&#123;</span><br><span class="line">               for (int j = 0; j &lt;100 ; j++) &#123;</span><br><span class="line">                   atomicInteger.incrementAndGet();</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;).start();</span><br><span class="line">       &#125;</span><br><span class="line">       // 等待线程执行完</span><br><span class="line">       while (Thread.activeCount()&gt;2)&#123;</span><br><span class="line">           Thread.yield();</span><br><span class="line">       &#125;</span><br><span class="line">       // 输出1000</span><br><span class="line">       System.out.println(atomicInteger.get());</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="原子更新数组类型"><a href="#原子更新数组类型" class="headerlink" title="原子更新数组类型"></a>原子更新数组类型</h1><p><strong>通过原子的方式更新数组里的某个元素。</strong>AtomicIntegerArray：原子更新整型数组里的元素。AtomicLongArray：原子更新长整型数组里的元素。AtomicReferenceArray：原子更新引用类型数组里的元素。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">/ 定义一个原子整数数组 初始值为0</span><br><span class="line">        AtomicIntegerArray atomicInteger = new AtomicIntegerArray(new int[]&#123;0,0,0&#125;);</span><br><span class="line">        // 开启十个线程 每个线程执行一百次</span><br><span class="line">        for (int i = 0; i &lt;10 ; i++) &#123;</span><br><span class="line">            new Thread(()-&gt;&#123;</span><br><span class="line">                for (int j = 0; j &lt;100 ; j++) &#123;</span><br><span class="line">                    // 计算数组位置 自增1</span><br><span class="line">                    atomicInteger.incrementAndGet(0);</span><br><span class="line">                    atomicInteger.incrementAndGet(1);</span><br><span class="line">                    atomicInteger.incrementAndGet(2);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125;</span><br><span class="line">        // 等待线程执行完</span><br><span class="line">        while (Thread.activeCount()&gt;2)&#123;</span><br><span class="line">            Thread.yield();</span><br><span class="line">        &#125;</span><br><span class="line">        // 输出 [1000,1000,1000]</span><br><span class="line">        System.out.println(atomicInteger.toString());</span><br></pre></td></tr></table></figure></p>
<p><strong>注意的是，数组通过构造方法传递进去，然后AtomicIntegerArray会将当前数组复制一份，所以当AtomicIntegerArray对内部的数组元素进行修改时，不会影响传入的数组。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">int[] value = &#123;1, 2&#125;;</span><br><span class="line">       AtomicIntegerArray ai = new AtomicIntegerArray(value);</span><br><span class="line">           ai.getAndSet(0, 3);</span><br><span class="line">           System.out.println(ai.get(0));</span><br><span class="line">           System.out.println(value[0]);</span><br><span class="line">       &#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>运行结果：<br>3<br>1</p>
</blockquote>
<h1 id="原子更新引用类型"><a href="#原子更新引用类型" class="headerlink" title="原子更新引用类型"></a>原子更新引用类型</h1><p><strong>通过原子方式更新引用类型。</strong>AtomicReference：原子更新引用类型；AtomicReferenceFieldUpdater：原子更新引用类型里的字段；AtomicMarkableReference：原子更新带有标记位的引用类型。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">        // 定义一个引用类型原子类</span><br><span class="line">        AtomicReference&lt;User&gt; reference = new AtomicReference&lt;&gt;();</span><br><span class="line">        // 定义个user 传入姓名和年龄</span><br><span class="line">        User user = new User(&quot;zhangsan&quot;, 10);</span><br><span class="line">        // 放入原子类中</span><br><span class="line">        reference.set(user);</span><br><span class="line">        // 定义个更新的user</span><br><span class="line">        User updateUser = new User(&quot;lisi&quot;, 20);</span><br><span class="line">        // 原子性更新user</span><br><span class="line">        reference.compareAndSet(user,updateUser);</span><br><span class="line">        // 输出 list</span><br><span class="line">        System.out.println(reference.get().getName());</span><br><span class="line">        // 输出 20</span><br><span class="line">        System.out.println(reference.get().getAge());</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="原子更新字段类"><a href="#原子更新字段类" class="headerlink" title="原子更新字段类"></a>原子更新字段类</h1><p><strong>通过原子方式更新引用类型的字段类型。</strong>AtomicIntegerFieldUpdater：原子更新整型的字段的更新器；AtomicLongFieldUpdater：原子更新长整型字段的更新器；AtomicStampedReference：原子更新带有版本号的引用类型，该类将整数值与引用关联起来，可用于原子的更新数据和数据的版本号，可以解决使用CAS进行原子更新时可能出现的ABA问题（下面有说）。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">// 定义一个引用字段类型原子类 更新user中的年龄</span><br><span class="line">      AtomicIntegerFieldUpdater&lt;User&gt; atomicIntegerFieldUpdater= AtomicIntegerFieldUpdater.newUpdater(User.class,&quot;age&quot;);</span><br><span class="line">      // 定义个user 传入姓名和年龄</span><br><span class="line">      User user = new User(&quot;zhangsan&quot;, 10);</span><br><span class="line">      // 年龄自增</span><br><span class="line">      int age = atomicIntegerFieldUpdater.incrementAndGet(user);</span><br><span class="line">      // 输出 11</span><br><span class="line">      System.out.println(age);</span><br></pre></td></tr></table></figure></p>
<p>代码注释都很明确，不明白的可以自己动手敲一敲很简单。</p>
<h1 id="原子类更新原理"><a href="#原子类更新原理" class="headerlink" title="原子类更新原理"></a>原子类更新原理</h1><p>就拿AtomicInteger为例子，每个类的方法都差不多，原理也基本一样，都是通过Unsafe来实现的，了解Unsafe之前得需要知道CAS。<strong>CAS全称是Compare And Swap 即比较并交换，使用乐观锁机制，包含三个操作数 —— 内存位置（V）、预期原值（A）和新值(B)， 如果内存位置的值与预期原值相匹配，那么才会将该位置值更新为新值 。否则，处理器不做任何操作。</strong>Unsafe就是使用这种方法来操作原子性，我们不能直接使用Unsafe，它是由bootstrap启动类加载器加载的，获取unsafe，unsafe存放就是内存位置的值（V）valueOffset存放的是在AtomicInteger中偏移量也就是预期原值，value使用volatile修饰保证内存的可见性，也就是我们get方法返回的值。<br><img src="https://s2.ax1x.com/2019/05/27/VZflgs.png" alt="在这里插入图片描述"></p>
<p>就拿比如incrementAndGet方法，调用getAndInt方法来进行自增。<img src="https://s2.ax1x.com/2019/05/27/VZfQ3j.png" alt="在这里插入图片描述"><br>实际上调用Unsafe中的方法，但是compareAndSwapInt方法已经被内置了，在1.7写的while(true)对内存值+1，而后使用cas修改变量的值，如果失败重试，直到成功。有兴趣的可以看下。<br><img src="https://s2.ax1x.com/2019/05/27/VZfMCQ.png" alt="在这里插入图片描述"><br><img src="https://s2.ax1x.com/2019/05/27/VZfu4g.png" alt="在这里插入图片描述"></p>
<h1 id="原子类的缺点"><a href="#原子类的缺点" class="headerlink" title="原子类的缺点"></a>原子类的缺点</h1><p>虽然原子在使用上简单，并且高效的解决了原子问题，但是还是有三个缺点。<br>1.<strong>循环时间长开销大。</strong>如果自旋CAS长时间不成功，会给CPU带来很大的开销。<br>2.<strong>只能保证一个共享变量的原子性操作。</strong>当对一个共享变量我们可以使用原子类，但是对于多个就无法保证了，这个时候就需要用锁来保证多个共享变量的原子性。<br>3.<strong>ABA问题。因为CAS在操作变量的时候，需要检查值有没有改变，如果没有发生改变则更新，但是如果一个值从A变成了B，又从B变成了A，那么使用CAS在进行检查的时候发现没有改变，但是实际上是变了的。</strong>再比如你的支付宝里有100（A），当你进行转账的时候转了50（B），由于网络延迟或者系统故障，没有及时到账，你再次转账这样相当于开了两个线程，这时候第一个线程成功了，OK转账成功，假如这时候有人给你转了50元，这时候你的余额又成了100（A），此时第二个线程就会发现余额还是100，它就会再次发生转账。解决方案也简单，在变量前追加版本号或者时间戳，每次变量更新都去更新版本号，比如A-&gt;B-&gt;A变成1A-&gt;2B-&gt;3A，JDK为我们提供了这种机制的更新AtomicStampedReference，还可以使用互斥锁来解决ABA问题。</p>

      
    </div>
    
    
    
	<div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2019/05/27/Java并发编程五Atomic原子类/">Java并发编程五Atomic原子类</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 zhaoSir 的个人博客">zhaoSir</a></p>
  <p><span>发布时间:</span>2019年05月27日 - 19:16</p>
  <p><span>最后更新:</span>2019年05月27日 - 19:25</p>
  <p><span>原始链接:</span><a href="/blog/2019/05/27/Java并发编程五Atomic原子类/" title="Java并发编程五Atomic原子类">https://zgsir.gitee.io/blog/2019/05/27/Java并发编程五Atomic原子类/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://zgsir.gitee.io/blog/2019/05/27/Java并发编程五Atomic原子类/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
</div>
   <div>
    
    <div>
    
        <div style="text-align:center;color: #111;font-size:16px;">-------------------------------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------------------------------</div>
    
</div>
    
    </div>
   

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Atomic/" rel="tag"><i class="fa fa-tag"> </i> Atomic</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/05/26/Java并发编程四synchronized和lock/" rel="next" title="Java并发编程四synchronized和lock">
                <i class="fa fa-chevron-left"></i> Java并发编程四synchronized和lock
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/05/28/Java并发编程六并发队列/" rel="prev" title="Java并发编程六并发队列">
                Java并发编程六并发队列 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80NDMyMC8yMDg1Mw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/images/head.jpeg" alt="zhaoSir">
            
              <p class="site-author-name" itemprop="name">zhaoSir</p>
              <p class="site-description motion-element" itemprop="description">让人迷茫的原因的只有一个，那就是本该拼搏的年纪，想得太多，做得太少。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#原子类"><span class="nav-number">1.</span> <span class="nav-text">原子类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原子更新基本类型"><span class="nav-number">2.</span> <span class="nav-text">原子更新基本类型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原子更新数组类型"><span class="nav-number">3.</span> <span class="nav-text">原子更新数组类型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原子更新引用类型"><span class="nav-number">4.</span> <span class="nav-text">原子更新引用类型</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原子更新字段类"><span class="nav-number">5.</span> <span class="nav-text">原子更新字段类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原子类更新原理"><span class="nav-number">6.</span> <span class="nav-text">原子类更新原理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原子类的缺点"><span class="nav-number">7.</span> <span class="nav-text">原子类的缺点</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script type="text/javascript" src="/blog/js/src/love.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaoSir</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">博客字总数&#58;</span>
    
    <span title="博客字总数">20.8k</span>
  
  
</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/blog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":320},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
</html>
